package com.zy.chat.util;


import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import  static com.zy.chat.util.RedisContants.*;



/**
 * Redis通用工具类
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;

    // =============================common============================
    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param map  项
     * @return true 成功 false失败
     */

    public boolean hsetadd(String key,Map map) {
        try {
            JSONObject jsonObject = new JSONObject(map);
            String json=jsonObject.toString();
            redisTemplate.opsForList().leftPush(key,json);
            redisTemplate.expire(key,MSG_TTL, TimeUnit.HOURS);
            redisTemplate.convertAndSend(key, json);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public boolean uploadFile(InputStream inputStream,String name){
        try {
            byte[] bytes = inputStream.readAllBytes();
            redisTemplate.opsForValue().set(name.getBytes(StandardCharsets.UTF_8),bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

}
